package com.baibei.order.detail;


import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.BuildConfig;
import com.baibei.ebec.sdk.TokenInfo;
import com.baibei.model.Area;
import com.baibei.model.BalanceInfo;
import com.baibei.model.BuyDirection;
import com.baibei.model.HttpResult;
import com.baibei.model.OrderInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.ResponseInfo;
import com.baibei.model.UserInfo;
import com.baibei.module.AreaHelper;
import com.baibei.module.BasicActivity;
import com.baibei.module.GlideApp;
import com.baibei.order.R;
import com.baibei.order.R2;
import com.baibei.order.trend.PriceTrendFragment;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.baibei.sdk.RxObservable;
import com.baibei.widget.BaibeiNumberBar;
import com.baibei.widget.PriceTextView;
import com.blankj.utilcode.utils.TimeUtils;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.Rx;
import com.rae.swift.session.SessionManager;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import static com.umeng.socialize.utils.ContextUtil.getPackageName;

/**
 * 接入行情的订单详情
 */
public class DefaultFragment extends OrderDetailFragment {

    @BindView(R2.id.iv_product)
    ImageView mIvProduct;
    @BindView(R2.id.iv_flag)
    ImageView mIvFlag;
    @BindView(R2.id.tv_product_name)
    TextView mTvProductName;
    @BindView(R2.id.tv_latest_price_value)
    TextView mTvLatestPrice;
    @BindView(R2.id.btn_price)
    TextView mBtnPrice;
    @BindView(R2.id.tv_income_total)
    PriceTextView mTvIncomeTotal;
    @BindView(R2.id.tv_income_precent)
    TextView mTvIncomePrecent;

    @BindView(R2.id.tv_order_type)
    TextView mTvOrderType;
    @BindView(R2.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R2.id.tv_order_date)
    TextView mTvOrderDate;
    @BindView(R2.id.tv_order_price)
    TextView mTvOrderPrice;
    @BindView(R2.id.tv_order_count)
    TextView mTvOrderCount;
    @BindView(R2.id.tv_order_amount)
    TextView mTvOrderAmount;
    @BindView(R2.id.tv_deposit)
    TextView mTvDeposit;
    @BindView(R2.id.tv_service_fee)
    TextView mTvServiceFee;
    //    @BindView(R2.id.tv_rise)
//    TextView mTvRise;
//    @BindView(R2.id.tv_decline)
//    TextView mTvDecline;

    private static final String ARG_PARAM1 = "param1";
    Unbinder unbinder;
    @BindView(R2.id.nb_up)
    BaibeiNumberBar nbUp;
    @BindView(R2.id.tv_up_cancel)
    TextView tvUpCancel;
    @BindView(R2.id.tv_up_confirm)
    TextView tvUpConfirm;
    @BindView(R2.id.ll_up_reset)
    LinearLayout llUpReset;
    @BindView(R2.id.tv_rise)
    TextView tvRise;
    @BindView(R2.id.tv_up_reset)
    TextView tvUpReset;
    @BindView(R2.id.fl_up_limit)
    FrameLayout flUpLimit;
    @BindView(R2.id.nb_down)
    BaibeiNumberBar nbDown;
    @BindView(R2.id.tv_down_cancel)
    TextView tvDownCancel;
    @BindView(R2.id.tv_down_confirm)
    TextView tvDownConfirm;
    @BindView(R2.id.ll_down_reset)
    LinearLayout llDownReset;
    @BindView(R2.id.tv_down)
    TextView tvDown;
    @BindView(R2.id.tv_down_reset)
    TextView tvDownReset;
    @BindView(R2.id.fl_down_limit)
    FrameLayout flDownLimit;

    private OrderInfo mInfo;
    private int RESET_UP_LIMIT = 1;
    private int RESET_DOWN_LIMIT = 2;

    public DefaultFragment() {
    }

    public static DefaultFragment newInstance(OrderInfo orderInfo) {
        DefaultFragment fragment = new DefaultFragment();
        Bundle args = new Bundle();
        args.putSerializable(ARG_PARAM1, orderInfo);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mInfo = (OrderInfo) getArguments().getSerializable(ARG_PARAM1);
        }
    }


    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.fragment_default;
    }

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        if (isAdded() && mInfo != null) {
            Log.i("minfo", mInfo.toString());

            mIvFlag.setImageResource(AreaHelper.getImageResource(Area.valueOf(mInfo.getArea())));

            //logo
            GlideApp.with(this).load(mInfo.getProductpic()).placeholder(R.color.dividerColor).into(mIvProduct);
            //商品名称
            mTvProductName.setText(mInfo.getName());
            //最新价格
            mTvLatestPrice.setText(getString(R.string.amount, Rx.formatPrice(mInfo.getLast())));
            //差价合计
            mTvIncomeTotal.setPriceWithPrecent(mInfo.getPrifitDifferent(), mInfo.getPrecent());
            //订购类型
            mTvOrderType.setText(mInfo.getBuydirection() == BuyDirection.DIRECTION_CURRENT_PRICE ? R.string.current_price_order : R.string.settle_price_order);
            //订单号
            mTvOrderNum.setText(mInfo.getOrdernum());
            //订单时间
            mTvOrderDate.setText(mInfo.getAddtime() == 0 ? null : TimeUtils.millis2String(mInfo.getAddtime()));
            //订货价
            mTvOrderPrice.setText(Rx.formatPrice(mInfo.getBuyprice()));
            //订货数量
            mTvOrderCount.setText(String.valueOf(mInfo.getCount()));
            //订货金额-----------------------
            mTvOrderAmount.setText(Rx.formatPrice(mInfo.getCount() * mInfo.getBuyprice()));
            //定金
            mTvDeposit.setText(Rx.formatPrice(mInfo.getBuyMoney()));
            //订货服务费
            mTvServiceFee.setText(Rx.formatPrice(mInfo.getFee()));
            //上升:
            tvRise.setText(mInfo.getToplimit() == 0 ? "无" : String.format("%s%%", mInfo.getToplimit() * 100));
            //下降:
            tvDown.setText(mInfo.getBottomlimit() == 0 ? "无" : String.format("%s%%", mInfo.getBottomlimit() * 100));
        }
    }

    @Override
    public void refresh(SparseArray<QuotationInfo> quotations) {
        if (isAdded()) {
            QuotationInfo quotationInfo = quotations.get(Rx.parseInt(mInfo.getProductid()));
            if (quotationInfo != null) {
//            LogUtils.e("订单详情中收到推送，并更新价格----原价格:" + mInfo.getLast() + ",推送过来的价格:" + quotationInfo.getMarketPrice());
                mInfo.setLast(quotationInfo.getMarketPrice());
                //刷新价格
                mTvLatestPrice.setText(getString(R.string.amount, Rx.formatPrice(mInfo.getLast())));
                mTvIncomeTotal.setPriceWithPrecent(mInfo.getPrifitDifferent(), mInfo.getPrecent());
            }
        }
    }

    @OnClick(R2.id.btn_price)
    public void onPriceTrendClick() {
        if (mInfo != null) {
            PriceTrendFragment priceTrendFragment = PriceTrendFragment.newInstance(mInfo.getProductid());
            priceTrendFragment.show(getChildFragmentManager(), "tag");
        }
    }

    private void reset(){
        RxObservable.create(ApiFactory.getInstance().getTradeApi().resetTopLimit(mInfo.getOrderid(),nbUp.getValue()+""),"resetLimit")
                .subscribe(new ApiDefaultObserver<HttpResult>() {
                    @Override
                    protected void onError(String s) {
                        ToastUtils.showLongToast("gagagagaq");
                        Log.i("emptyh",s);
                    }

                    @Override
                    protected void accept(HttpResult info) {
                        Log.i("emptyh",info.getCode());
                        ToastUtils.showLongToast("hahahhah");
                    }

                });
    }

    private void resetLimit(final int type) {

        TokenInfo userToken = SessionManager.getDefault().getUserToken();
        HashMap<String, String> data = new HashMap<>();
        data.put((type==RESET_UP_LIMIT)?"toplimit":"bottomlimit",(type==RESET_UP_LIMIT)?nbUp.getValue()+"":nbDown.getValue()+"");
        data.put("orderId", mInfo.getOrderid());
        HashMap<String, Object> map = new HashMap<>();
        map.put("exchange", BuildConfig.EXCHANGE);
        map.put("requestId", UUID.randomUUID().toString());
        if (SessionManager.getDefault().getUser() != null){
            map.put("userId",((UserInfo)SessionManager.getDefault().getUser()).getUserId()+"");
        } else {
            map.put("userId","0");
        }
        map.put("platform", "server");
        map.put("deviceId", "BB-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString());
        map.put("timestamp", "" + System.currentTimeMillis());
        map.put("version", getVersion());
        map.put("memberChannel", ApiConstant.MEMBER_CHANNEL);
        map.put("appKey", BuildConfig.APPKEY);
        map.put("accessToken", userToken.getAccessToken());
        map.put("refreshToken", userToken.getRefreshToken());
        map.put("data", data);
        Gson gson = new Gson();
        String s = gson.toJson(map);

        OkHttpClient client = new OkHttpClient();
        String upUrl = BuildConfig.API_BASE_URL + "cbclient/api/oauth/order/toplimit/update";
        String downUrl = BuildConfig.API_BASE_URL + "cbclient/api/oauth/order/bottomlimit/update";
        RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
        Request request = new Request.Builder()
                .post(requestBody)
                .url(type==RESET_UP_LIMIT?upUrl:downUrl)
                .build();
        Call call = client.newCall(request);
        try {
            Response response = call.execute();
            JSONObject json = new JSONObject(response.body().string());
            Log.i("minfo", json.toString());

            if (!"SUCCESS".equals(json.optString("code"))) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        ToastUtils.showLongToast("调整失败，请重试");
                    }
                });
                return;
            }
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    ToastUtils.showLongToast("调整成功");
                    if (type == RESET_UP_LIMIT){
                        tvRise.setText(nbUp.getValue() + ".0%");
                        llUpReset.setVisibility(View.INVISIBLE);
                        flUpLimit.setVisibility(View.VISIBLE);
                    } else {
                        tvDown.setText(nbDown.getValue()+".0%");
                        llDownReset.setVisibility(View.INVISIBLE);
                        flDownLimit.setVisibility(View.VISIBLE);
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getVersion() {
        try {
            return getContext().getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_META_DATA).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.0";
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R2.id.tv_up_cancel, R2.id.tv_up_confirm, R2.id.tv_up_reset,
                R2.id.tv_down_cancel, R2.id.tv_down_confirm, R2.id.tv_down_reset})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.tv_up_cancel) {
            llUpReset.setVisibility(View.INVISIBLE);
            flUpLimit.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.tv_up_confirm) {
            if (nbUp.getValue() == 0){
                ToastUtils.showLongToast("调整数值不可以为0");
                return;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    resetLimit(RESET_UP_LIMIT);
//                    reset();
                }
            }).start();
        } else if (view.getId() == R.id.tv_up_reset){
            flUpLimit.setVisibility(View.INVISIBLE);
            llUpReset.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.tv_down_cancel){
            llDownReset.setVisibility(View.INVISIBLE);
            flDownLimit.setVisibility(View.VISIBLE);
        } else if (view.getId() == R.id.tv_down_confirm){
            if (nbDown.getValue() == 0){
                ToastUtils.showLongToast("调整数值不可以为0");
                return;
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    resetLimit(RESET_DOWN_LIMIT);
                }
            }).start();
        } else {
            flDownLimit.setVisibility(View.INVISIBLE);
            llDownReset.setVisibility(View.VISIBLE);
        }
    }
}
